import sshtransmission as T
from os import system, linesep, sep
from KThread import KThread as kthread
from commands import getoutput
import gtk
import pango
import gtk.glade
import gobject

def setc_(reference):
    global _
    _ = reference

class Connection(object):
    def __init__(self):
        self.session = None
        self.auxsession = None
        self.ps_command = "echo $(ps -fC transmission-daemon|grep $USER)"
        self.remotebin = "transmission-remote"
        self.command = self.remotebin + " -t daemon"
        self.to_exec = [] # Commands to execute
        self.to_set = []  # Options to send using transmission-remote commands
        self.killdaemon = False
        self.tthread_running = False
        self.protocol = -1 # 0 - Local, 1 - ssh

    def session_logout(self):
        if self.protocol == 1:
            if self.session.isalive():
                self.session.logout()
            if self.auxsession.isalive():
                self.auxsession.logout()
            self.session.close()
            self.auxsession.close()
        self.protocol = -1

    def store_option(self,conflictive_list,new_ones):
        i = 0
        while i < len(self.to_set):
            removed = False
            for j in conflictive_list:
                if j in self.to_set[i]:
                    self.to_set.pop(i)
                    removed = True
                    break
            if not removed:
                i += 1
        self.to_set = self.to_set + new_ones

    def new_local_session(self,verify=True):
        toreturn = [-1,None,False]
        commands = ["which zenity",
                    "which transmission-remote",
                    "which transmission-daemon",
                    "export LANG='en_US'",
                    self.ps_command]
        retorno = ["","Dummy"]
        for i in commands:
            retorno[0] += i + linesep + getoutput(i).strip() + linesep
        if retorno != None and len(retorno)==2:
            toreturn[1] = retorno[1]
            retorno = retorno[0].replace("\r\n",linesep).replace("\r",linesep).replace("\n",linesep)
            responses = []
            for i in range(len(commands)):
                response = retorno.split(commands[i])[1]
                if i < len(commands) - 1:
                    response = response.split(commands[i+1])[0]
                responses.append(response.strip())
            if verify:
                if responses[0]=="":
                    toreturn[0] = 2
                else:
                    toreturn[0] = 1
                for i in responses[1:3]:
                    if i=="":
                        toreturn[0] = 0
                if self.ps_command_parse(responses[4])>-1:
                    toreturn[2] = True
        return toreturn

    def new_ssh_session(self,ip,user,passw,port,X=False,verify=True):
        '''Starts new session, responses [state,session,running_daemon]
           States:
            -1 - Unknown
             0 - Without transmission-remote or daemon
             1 - Ok'''
        toreturn = [-1,None,False]
        commands = []
        if verify:
            commands = [None,
                        "which transmission-remote",
                        "which transmission-daemon",
                        "export LANG='en_US'",
                        self.ps_command]
        retorno = T.ssh(ip,user,passw,port=port,commands=commands,connect_display=X,logout=False)
        if retorno[0] == 1:
            toreturn[1] = retorno[1]
            
            if verify:
                toreturn[0] = 1
                for i in retorno[2][1:3]:
                    if i.strip()=="":
                        torreturn[0] = 0
                        break

                if self.ps_command_parse(retorno[2][4])>-1:
                    toreturn[2] = True
        return toreturn

    def exec_commands_with_session(self,commands=[],session=None,Y=False):
        '''Parse all commands to send to unique, and return a list of outputs'''
        retorno = None

        if len(commands)>0:
            if self.protocol==0:
                separator1 = "db63e5a1d309865cc47ea96a606d5fe5"
                separator2 = "38d5f0294827d631988217951d8dec2d"
                tosend = "echo "+separator2
                for i in commands[:-1]:
                    tosend += "&&" + i + "&&echo "+separator1
                tosend += "&&" + commands[-1]
                output = getoutput(tosend)
                output = output.replace("\r\n",linesep).replace("\r",linesep).replace("\n",linesep).strip()
                retorno = output.split(separator2)[-1].split(separator1)
            elif self.protocol==1:
                if session!=None:
                    retorno = T.ssh(T.ip,T.user,T.passw,port=T.port,session=session,commands=commands,logout=False,connect_display=Y)
                    
                if session==None:
                    retorno = T.ssh(T.ip,T.user,T.passw,port=T.port,commands=commands,logout=True,connect_display=Y)
                
                if retorno[0] == 1 or (session==1 and retorno[0]==-1):
                    retorno = retorno[2]
                else:
                    print ["Cannot connect to server.",
                            None,
                            "Cannot login on server.",
                            "Bad session given, contact to developers.",
                            "Cannot send commands, remote session is probably broken."][retorno[0]]
                    retorno = None

        return retorno

    def exec_commands(self,commands=[]):
        return self.exec_commands_with_session(commands,self.session)

    def daemon_running(self):
        if self.session != None:
            output = self.ps_command_parse(self.exec_commands([self.ps_command])[0])
            if output!=-1:
                return (True,output)

        return (False,-1)

    def ps_command_parse(self,output):
        #print output
        if output!=None and output.strip() and \
            output.strip().split()[1].isdigit():
                return int(output.strip().split()[1])
        return -1

    def stop_daemon(self):
        self.exec_commands(["transmission-remote -q"])

    def start_daemon(self):
        self.exec_commands(["transmission-daemon"])

    def do(self):
        send_commands = []
        if len(self.to_exec)>0:
            send_commands += self.to_exec[:]
            self.to_exec = []

        if len(self.to_set)>0:
            send_commands += self.to_set[:]
            self.to_set = []

        # Execute commands
        send_commands += [self.command+" -i",self.command+" -l"]
        #print send_commands
        a = self.exec_commands(send_commands)
        if a == None:
            return (False, "error")
        else:
            command_output_list = a

        errorlist = ['transmission-remote: failed to connect to socket file:']
        if len(send_commands)!=len(command_output_list):
            return (False,2)
        
        for i in range(len(errorlist)):
            for j in command_output_list:
                if errorlist[i] in j:
                    return (False, i)

        return (True,command_output_list)

    def send_torrents(self,list=[],ufo=False):
        if ufo:
            while self.tthread_running:
                sleep(0.1)
            self.tthread_running=True
            if self.protocol==0:
                to_send = []
                for i in list:
                    if exists(i) and isfile(i):
                        to_send.append("transmission-remote -a "+i)
                self.exec_commands(to_send)
            elif self.protocol ==1:
                # TODO: New method
                T.send_to_transmission(T.ip,T.user,T.passw,T.port,list,options=self.command,session=self.auxsession)
            self.tthread_running=False
        else:
            a = kthread(target=self.send_torrents,kwargs={"list":list,"ufo":True})
            a.start()
            
